package com.leyou.gateway.task;

import com.leyou.auth.client.AuthClient;
import com.leyou.gateway.properties.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: wangzibeng
 * Date: 2019/5/16 0016
 * Time: 15:28
 */
@Slf4j
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class PrivilegeTokenHolder {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private AuthClient authClient;
    private String token;
    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;
    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;

    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    private void loadToken() throws InterruptedException {
        // 获取token
        while (true) {
            try {
                this.token = authClient.authenticate(jwtProperties.getPrivilege().getId(), jwtProperties.getPrivilege().getSecret());
                log.info("【gateway】加载成功，时间为{}", LocalDateTime.now().toString());
                break;
            } catch (Exception e) {
                log.error("【gateway】加载token失败", e);
            }
            // 休眠10秒后重试
            Thread.sleep(TOKEN_RETRY_INTERVAL);
        }
    }

    public String getToken() {
        return token;
    }
}
